/*
 * author      : 吴中勤 
 * date        : 2018/11/11
 * description : TODO
 */

package org.wzq.learn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Service
public class TradeService {

    private static final Logger logger = LoggerFactory.getLogger(TradeService.class);

    @Autowired
    private RestTemplate restTemplate;


    public String hiShopInThread(String name) {
        Task task = new Task(restTemplate, name);
        FutureTask<String> futureTask = new FutureTask<String>(task);
        Thread thread = new Thread(futureTask);
        thread.start();

        while (!futureTask.isDone()) {
            try {
                if (logger.isInfoEnabled()) logger.info("sleep, wait futureTask done");
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            return futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static class Task implements Callable<String> {
        private final RestTemplate restTemplate;
        private final String name;

        public Task(RestTemplate restTemplate, String name) {
            this.restTemplate = restTemplate;
            this.name = name;
        }

        @Override
        public String call() throws Exception {
            return restTemplate.getForObject("http://shop-service/shop/ruok?name=" + name, String.class);
        }
    }
}
